package org.bonorsoft.common.dingapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.taobao.api.ApiException;
import org.bonorsoft.common.constant.CacheConstant;
import org.bonorsoft.common.constant.URLConstant;
import org.springframework.cache.annotation.Cacheable;

public class DingdingUser {

    @Cacheable(value = CacheConstant.DING_USER_INFOR, key = "#id")
    public static String getUser(String id) {
        String result = "";
        try {
            DingTalkClient client = new DefaultDingTalkClient(URLConstant.GET_USER);
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(id);
            OapiV2UserGetResponse rsp = client.execute(req, AccessTokenUtil.getToken());
            System.out.println(rsp.getBody());
            JSONObject obj = JSON.parseObject(rsp.getBody());
            result = obj.getString("result");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getuserId(String code) {
        String userId = "";
        try {
            DingTalkClient client = new DefaultDingTalkClient(URLConstant.GET_USERINFO);
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.setCode(code);
            request.setHttpMethod("GET");
            OapiUserGetuserinfoResponse response = client.execute(request, AccessTokenUtil.getToken());
            userId = response.getUserid();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return userId;
    }


    public static String getUserList(Long depart_id, Long cursor, Long size) {
        String result = "";
        try {
            DingTalkClient client = new DefaultDingTalkClient(URLConstant.USER_LIST);
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            req.setDeptId(depart_id);
            req.setCursor(cursor);
            req.setSize(size);
            OapiV2UserListResponse rsp = client.execute(req, AccessTokenUtil.getToken());
            System.out.println(rsp.getBody());
            JSONObject obj = JSON.parseObject(rsp.getBody());
            result = obj.getString("result");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return result;
    }


}
